/**
 * 
 */
package org.crazydays.i18n;


import java.text.MessageFormat;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Messages
 */
public final class Messages
{
    /** log */
    public final static Logger LOGGER = LoggerFactory.getLogger(Messages.class);

    /** property: messages path */
    public final static String PROPERTY_MESSAGES_PATH = "messages.path";

    /** default: messages path */
    public final static String DEFAULT_MESSAGES_PATH = "messages";

    /** messages */
    private volatile static Messages messages;

    /**
     * Get messages instance.
     * 
     * @return Messages
     */
    public static Messages getInstance()
    {
        if (messages == null) {
            synchronized (Messages.class) {
                if (messages == null) {
                    messages = new Messages();
                }
            }
        }

        return messages;
    }

    /** locale */
    protected Locale locale;

    /** resource bundle */
    protected ResourceBundle resourceBundle;

    /**
     * Messages constructor.
     */
    private Messages()
    {
        initialize();
    }

    /**
     * Initialize.
     */
    protected void initialize()
    {
        String messagesPath = System.getProperty(PROPERTY_MESSAGES_PATH);
        if (messagesPath == null) {
            messagesPath = DEFAULT_MESSAGES_PATH;
        }

        try {
            resourceBundle =
                ResourceBundle.getBundle(messagesPath, Locale.getDefault());
        } catch (MissingResourceException e) {
            LOGGER.warn("Unable to load messages {}", messagesPath);
        }

        // log resource bundle keys
        if (LOGGER.isDebugEnabled()) {
            for (String key : resourceBundle.keySet()) {
                LOGGER.debug("{}={}", key, resourceBundle.getString(key));
            }
        }
    }

    /**
     * Get message.
     * 
     * @param key Key
     * @return Message
     */
    public String getMessage(String key)
    {
        try {
            return resourceBundle.getString(key);
        } catch (MissingResourceException e) {
            LOGGER.warn("Missing resource {}", key);
            return "[" + key.toUpperCase() + "]";
        }
    }

    /**
     * Format message.
     * 
     * @param key Key
     * @param arguments Arguments
     * @return Formatted message
     */
    public String format(String key, Object... arguments)
    {
        return MessageFormat.format(getMessage(key), arguments);
    }
}
